<template>
  <div class="student-personal-center">
    <!-- 标题 -->
    <div class="page-header">
      <h1 class="page-title">{{ $t('assets.personalCenter.title') }}</h1>
    </div>

    <!-- 个人信息卡片 -->
    <div class="profile-section">
      <el-card class="profile-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>{{ $t('assets.personalCenter.basicInfo') }}</h3>
          </div>
        </template>

        <div class="profile-content">
          <!-- 头像和基本信息 -->
          <div class="profile-header">
            <div class="avatar-section">
              <el-avatar :size="100" class="user-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <el-button type="primary" size="small" class="upload-btn">
                {{ $t('assets.personalCenter.uploadAvatar') }}
              </el-button>
            </div>

            <div class="basic-info">
              <h2 class="username">{{ userInfo.username }}</h2>
              <p class="user-role">{{ $t('common.student') }}</p>
              <div class="user-meta">
                <el-tag type="info">{{ userInfo.studentId }}</el-tag>
                <el-tag type="success">{{ userInfo.className }}</el-tag>
              </div>
            </div>
          </div>

          <!-- 详细信息表格 -->
          <div class="info-table">
            <el-descriptions :column="2" border>
              <el-descriptions-item :label="$t('assets.personalCenter.username')">
                {{ userInfo.username }}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('assets.personalCenter.loginName')">
                {{ userInfo.loginName }}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('assets.personalCenter.phone')">
                <div class="editable-field">
                  <span>{{ userInfo.phone }}</span>
                  <el-button type="text" size="small" @click="handleModifyPhone">
                    {{ $t('assets.personalCenter.modify') }}
                  </el-button>
                </div>
              </el-descriptions-item>
              <el-descriptions-item :label="$t('assets.personalCenter.email')">
                <div class="editable-field">
                  <span>{{ userInfo.email }}</span>
                  <el-button type="text" size="small" @click="handleModifyEmail">
                    {{ $t('assets.personalCenter.modify') }}
                  </el-button>
                </div>
              </el-descriptions-item>
              <el-descriptions-item :label="$t('assets.personalCenter.studentId')">
                {{ userInfo.studentId }}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('assets.personalCenter.className')">
                {{ userInfo.className }}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('assets.personalCenter.createTime')">
                {{ userInfo.createTime }}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('assets.personalCenter.lastLogin')">
                {{ userInfo.lastLoginTime || $t('assets.personalCenter.never') }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-card>
    }

    <!-- 学习统计 -->
    <el-card class="stats-card">
      <div class="stats-header">
        <h3>学习统计</h3>
      </div>

      <div class="stats-content">
        <div class="stat-item">
          <div class="stat-number">{{ learningStats.completedTasks }}</div>
          <div class="stat-label">已完成任务</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ learningStats.pendingTasks }}</div>
          <div class="stat-label">待完成任务</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ learningStats.totalScore }}</div>
          <div class="stat-label">总分数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ learningStats.averageScore }}%</div>
          <div class="stat-label">平均分</div>
        </div>
      </div>
    </el-card>

    <!-- 安全设置 -->
    <el-card class="security-card">
      <div class="security-header">
        <h3>{{ $t('assets.personalCenter.securitySettings') }}</h3>
      </div>

      <div class="security-content">
        <!-- 登录密码 -->
        <div class="security-item">
          <div class="security-label">{{ $t('assets.personalCenter.loginPassword') }}</div>
          <div class="security-desc">{{ passwordDesc }}</div>
          <el-button type="text" class="security-action" @click="handleModifyPassword">{{ $t('assets.personalCenter.modify') }}</el-button>
        </div>

        <!-- 安全手机 -->
        <div class="security-item">
          <div class="security-label">{{ $t('assets.personalCenter.securityPhone') }}</div>
          <div class="security-desc">{{ phoneSecurityDesc }}</div>
          <el-button type="text" class="security-action" @click="handleModifySecurityPhone">{{ $t('assets.personalCenter.modify') }}</el-button>
        </div>

        <!-- 安全邮箱 -->
        <div class="security-item">
          <div class="security-label">{{ $t('assets.personalCenter.securityEmail') }}</div>
          <div class="security-desc">{{ emailSecurityDesc }}</div>
          <el-button type="text" class="security-action" @click="handleSetSecurityEmail">{{ $t('assets.personalCenter.setup') }}</el-button>
        </div>
      </div>
      <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSave" :loading="saving">{{ $t('assets.personalCenter.save') }}</el-button>
      <el-button @click="handleReset">{{ $t('assets.personalCenter.reset') }}</el-button>
    </div>
    </el-card>

    
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { t as $t } from '@/plugins/simpleI18n'
import { photosStorage, type PhotoData } from '@/utils/photosDB'

// 用户信息接口
interface StudentUserInfo {
  username: string
  loginName: string
  createTime: string
  phone: string
  email: string
  studentId: string
  className: string
}

// 学习统计接口
interface LearningStats {
  completedTasks: number
  pendingTasks: number
  totalScore: number
  averageScore: number
}

// 响应式数据
const saving = ref(false)

// 学生用户信息数据
const userInfo = ref<StudentUserInfo>({
  username: '张小明',
  loginName: 'zhangxiaoming',
  createTime: '2024-09-01 08:00:00',
  phone: '138*****88',
  email: '138*****88@qq.com',
  studentId: 'STU202401001',
  className: '三年级一班'
})

// 学习统计数据
const learningStats = ref<LearningStats>({
  completedTasks: 15,
  pendingTasks: 3,
  totalScore: 1350,
  averageScore: 85
})

// 计算属性 - 安全设置描述
const passwordDesc = computed(() => {
  return $t('assets.personalCenter.passwordDesc')
})

const phoneSecurityDesc = computed(() => {
  return `已绑定：${userInfo.value.phone.replace(/(\d{3})\d{5}(\d{2})/, '$1*****$2')}`
})

const emailSecurityDesc = computed(() => {
  return $t('assets.personalCenter.emailSecurityDesc')
})

// 方法
const handleModifyPhone = () => {
  ElMessage.info('修改手机号码功能')
}

const handleModifyEmail = () => {
  ElMessage.info('修改邮箱功能')
}

const handleModifyPassword = () => {
  ElMessage.info('修改密码功能')
}

const handleModifySecurityPhone = () => {
  ElMessage.info('修改安全手机功能')
}

const handleSetSecurityEmail = () => {
  ElMessage.info('设置安全邮箱功能')
}

const handleSave = async () => {
  saving.value = true
  try {
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success($t('assets.personalCenter.saveSuccess'))
  } catch (error) {
    ElMessage.error($t('assets.personalCenter.saveFailed'))
  } finally {
    saving.value = false
  }
}

const handleReset = () => {
  // 重置表单数据
  userInfo.value = {
    username: '张小明',
    loginName: 'zhangxiaoming',
    createTime: '2024-09-01 08:00:00',
    phone: '138*****88',
    email: '138*****88@qq.com',
    studentId: 'STU202401001',
    className: '三年级一班'
  }
  learningStats.value = {
    completedTasks: 15,
    pendingTasks: 3,
    totalScore: 1350,
    averageScore: 85
  }
  ElMessage.info($t('assets.personalCenter.resetSuccess'))
}

// 图片处理相关方法
const handleAvatarUpload = async (photoData: PhotoData) => {
  try {
    // 为头像图片添加特殊标记
    const avatarPhoto = {
      ...photoData,
      category: 'avatar',
      userId: userInfo.value.loginName,
      uploadTime: new Date().toISOString()
    }

    await photosStorage.savePhoto(avatarPhoto)
    ElMessage.success($t('assets.personalCenter.avatarUploadSuccess'))

    // 可以在这里更新用户头像显示
    console.log('头像已上传:', avatarPhoto)
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error($t('assets.personalCenter.avatarUploadError'))
  }
}

// 加载用户相关图片
const loadUserPhotos = async () => {
  try {
    const photos = await photosStorage.getAllPhotos()
    const userPhotos = photos.filter(photo =>
      photo.category === 'avatar' && photo.userId === userInfo.value.loginName
    )
    console.log('用户图片:', userPhotos)
    return userPhotos
  } catch (error) {
    console.error('加载用户图片失败:', error)
    return []
  }
}

// 获取学习数据统计图片
const getStudentDataPhotos = async () => {
  try {
    const photos = await photosStorage.getAllPhotos()
    const studentPhotos = photos.filter(photo =>
      photo.category === 'homework-submission' ||
      photo.category === 'learning-task'
    )
    return studentPhotos
  } catch (error) {
    console.error('获取学习数据图片失败:', error)
    return []
  }
}

onMounted(() => {
  console.log('学生个人中心加载完成')
  // 加载用户相关图片
  loadUserPhotos()
})
</script>

<style scoped>
.student-personal-center {
  padding: 0;
  max-width: 1200px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 个人信息区域 */
.profile-section {
  margin-bottom: 24px;
}

.profile-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.profile-content {
  padding: 0;
}

/* 个人资料头部 */
.profile-header {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  font-size: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.upload-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.upload-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.basic-info {
  flex: 1;
}

.username {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
}

.user-role {
  margin: 0 0 16px 0;
  font-size: 16px;
  opacity: 0.9;
}

.user-meta {
  display: flex;
  gap: 12px;
}

.user-meta .el-tag {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

/* 信息表格 */
.info-table {
  padding: 24px;
}

.editable-field {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
}

.info-row {
  display: flex;
  align-items: center;
  gap: 16px;
  line-height: 1.5;
}

.info-label {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
}

.info-value {
  font-size: 14px;
  color: #303133;
  min-width: 120px;
}

.phone-label,
.email-label,
.class-label {
  font-size: 14px;
  color: #606266;
  margin-left: 40px;
  min-width: 80px;
}

.phone-value,
.email-value,
.class-value {
  font-size: 14px;
  color: #303133;
  min-width: 120px;
}

.modify-btn {
  color: #409EFF;
  padding: 0;
  font-size: 14px;
  margin-left: 8px;
}

.modify-btn:hover {
  color: #66b1ff;
}

/* 学习统计卡片 */
.stats-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: none;
}

.stats-header {
  padding: 20px 20px 0 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.stats-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px 0;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 0 20px 20px 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 安全设置卡片 */
.security-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: none;
}

.security-header {
  padding: 20px 20px 0 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.security-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px 0;
}

.security-content {
  padding: 0 20px 20px 20px;
}

.security-item {
  display: flex;
  align-items: flex-start;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-label {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
}

.security-desc {
  flex: 1;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  margin: 0 16px;
}

.security-action {
  color: #409EFF;
  padding: 0;
  font-size: 14px;
  flex-shrink: 0;
}

.security-action:hover {
  color: #66b1ff;
}

/* 操作栏 */
.action-bar {
  display: flex;
  gap: 16px;
  padding: 20px 0;
}

.action-bar .el-button {
  padding: 10px 24px;
  font-size: 14px;
}
</style>
